import { Config, Inject, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { In, Repository } from 'typeorm';
import { BizOrderListEntity } from '../entity/list';
import { BizOrderProofListEntity } from '../entity/proofList';
import { BizOrderDetailEntity } from '../entity/detail';
import { Context } from '@midwayjs/koa';

/**
 * 订单列表服务
 */
@Provide()
export class BizOrderProofListService extends BaseService {
  @Inject()
  ctx: Context;

  @InjectEntityModel(BizOrderProofListEntity)
  bizOrderProofListEntity: Repository<BizOrderProofListEntity>;
  @InjectEntityModel(BizOrderListEntity)
  bizOrderListEntity: Repository<BizOrderListEntity>;
  @InjectEntityModel(BizOrderDetailEntity)
  bizOrderDetailEntity: Repository<BizOrderDetailEntity>;

  async page(
    query: any,
    option: any,
    connectionName?: any
  ): Promise<{
    orderInfo: any;
    orderDetail: any;
    list: any;
    pagination: { page: number; size: number; total: number };
  }> {
    const { page, size, sort, order, orderId } = query;
    const { fieldEq, keyWordLikeFields } = option;

    const whereStrs = [];
    fieldEq.forEach((key: any) => {
      const queryStr = query[key];

      if (queryStr !== undefined) {
        whereStrs.push(`OPL.${key} = '${queryStr}'`);
      }
    });
    keyWordLikeFields.forEach((key: any) => {
      const { keyWord } = query;
      keyWord !== undefined && whereStrs.push(`${key} like '%${keyWord}%'`);
    });

    const [orderInfo, orderDetailInfo, [{ total }], orderList] =
      await Promise.all([
        this.bizOrderListEntity.findOneBy({ id: orderId }),
        this.bizOrderDetailEntity.findOneBy({ orderId }),
        this.nativeQuery(`
        SELECT
          COUNT(*) AS total
        FROM
          biz_order_proof_list OPL
        ${whereStrs.length ? `WHERE ${whereStrs.join(' && ')}` : ''};
      `),
        this.nativeQuery(`
        SELECT
          OPL.*,
          WL.name,
          WL.phone
        FROM
          biz_order_proof_list OPL
        LEFT JOIN
          biz_worker_list WL ON OPL.workerId = WL.id
        ${whereStrs.length ? `WHERE ${whereStrs.join(' && ')}` : ''}
        ORDER BY ${order ? order : 'OPL.id'} ${
          sort ? sort.toUpperCase() : 'DESC'
        }
        LIMIT ${(page - 1) * size},${size};
      `),
      ]);

    return {
      orderInfo,
      orderDetail: orderDetailInfo.content,
      list: orderList,
      pagination: {
        page,
        size,
        total: Number(total),
      },
    };
  }

  async checkoutUploadProof(orderId: number, workerId: number) {
    const data = await this.bizOrderProofListEntity.findOneBy({
      orderId,
      workerId,
    });

    if (data) {
      delete data.createTime;
      delete data.updateTime;
    }

    return data;
  }
}
